#include "Network.h"
#include <QDebug>
#include <QString>

//处理密码/任务列表/数据项
NetData *NetData::Net=nullptr;

QString GetHead(QByteArray &Data,int &pos);
QVector<QString> GetBody_list(QByteArray &Data,const int size,int &pos);
bool GetBody_post(QByteArray &Data,const int size,int &pos);
int GetSize(QByteArray &Data,int &pos);
//获取单例
NetData *NetData::GetNetWork()
{
    if(Net==nullptr)
    {
        Net=new NetData();
    }
    return Net;
}

NetData::NetData()
{
toAddress.setAddress("192.168.81.200");
toPort=3666;
Client=new QTcpSocket();

Number.clear();
 start=false;
 password=false;

 t.start();
//监听连接状态
 connect(&t,&LinkNetThread::tim,this,[=](){
if(!start)
{
    Client->connectToHost(toAddress, toPort);
    emit link_is_no();
}
});

 //连接
connect(Client,&QTcpSocket::connected,this,[&](){
    start=true;
    qDebug()<<"连接到达"<<endl;
 });

//接收连接并判断数据包类型
//定义2种发送头(Get)(Post)
connect(Client,&QTcpSocket::readyRead,this,[&](){
//获取请求头/获得主体
    QByteArray readData;
    readData.append(Client->readAll());

    int pos=0;
    qDebug()<<"data:"<<readData<<" size:"<<readData.size()<<endl;

    //根据请求头(head)不同 获取主体方式

    while(pos<readData.size())
    {
    QString head=GetHead(readData,pos);
    if(head.isEmpty()){
        break;
    }
    //获取大小
    int size=GetSize(readData,pos);
    if(size<=0)
    {
        break;
    }
    if (size == -1 || pos + size > readData.size()) {
               // 数据不完整，等待更多数据
               break;
           }

    qDebug()<<"haed:"<<head<<"size:"<<size<<endl;

        if(head=="Get")
          {
              Number=GetBody_list(readData,size,pos);
              emit geted();
         }else if(head=="Post")
          {
             password=GetBody_post(readData,size,pos);
              emit posted(password);
          }else if(head=="Register"){
            password=GetBody_post(readData,size,pos);
            emit registed(password);
        }

    }
});
//断开
connect(Client,&QTcpSocket::disconnected,this,[&](){
start=false;
qDebug()<<"alos cut link..."<<endl;
Client->close();
});

}

NetData::~NetData()
{
    delete Client;

}

int GetSize(QByteArray &Data,int &pos){
    QByteArray size;
    if(Data.at(pos)==' ')
    {
        pos++;
    }
    size.push_back(Data.at(pos++));
    size.push_back(Data.at(pos++));
    return size.toInt();

}

bool GetBody_post(QByteArray &Data,const int size,int &pos){
    QString code;
    int j=0;
    while(j<size)
    {
        if(Data.at(pos)==' ')
        {
           continue;
        }
       code.push_back(Data.at(pos));
       pos++;
       j++;
    }

    if(code=="True")
    {
        return true;
    }
    return false;
}

QVector<QString> GetBody_list(QByteArray &Data,const int size,int &pos){
    QString code;
    QVector<QString> listCode;
    int i=0;
    while(i<size)
    {  
        //遇到空格前的数据写入String数组中
        if(Data.at(pos)==' ')
        {
            i++;
            pos++;
            if(code.isNull())
            {
                 continue;
            }
           listCode.push_back(code);
           code.clear();
           continue;
        }
       code.push_back(Data.at(pos));
    i++;
    pos++;
    }
    listCode.push_back(code);

    return  listCode;
}

//获取头
QString GetHead(QByteArray &Data,int &pos){
    QString headStr;
    int startPos=pos;
   for(int i=pos;i<Data.size();i++)
   {
    if(Data.at(i)==' ')
    {
        pos=i;
        return Data.mid(startPos, i - startPos);
    }
    if(!((Data.at(i)>='A'&&Data.at(i)<='Z')||(Data.at(i)>='a'&&Data.at(i)<='z')))
    {
        return QString();
    }
}
return QString();
}

//Post请求
bool NetData::Post(QString pass,QString accounct){
if(start==true)
{
    QByteArray post;
    QByteArray accoun;//账号密码
    //拼接大小/账号密码
    accoun.push_back(accounct.toUtf8());
    accoun.push_back(" ");
    accoun.push_back(pass.toUtf8());

    post.push_back("Post ");
    if(accoun.size()>9)
    {
        post.push_back(QByteArray::number(accoun.size()));
    }else{
        post.push_back("0");
        post.push_back(QByteArray::number(accoun.size()));
    }
    post.push_back(accoun);
 qDebug()<<"post value:"<<post<<endl;
    qint64 ret=Client->write(post);
 return ret>0 ?true :false;
}
return false;
}

//Get请求
bool NetData::Get(int size){
    if(start==true)
    {
        QByteArray send;
        send.push_back("Get");
        send.push_back(" ");
        send.push_back(QByteArray::number(size));

     qint64 ret=Client->write(send);

     return ret>0 ?true :false;
    }
    return false;
}

//Register请求
bool NetData::Registerd(QString accounct,QString passwd)
{
    QByteArray Regist;
    Regist.push_back("Register ");

    QByteArray accoun;//账号密码
    accoun.push_back(accounct.toUtf8());
    accoun.push_back(" ");
    accoun.push_back(passwd.toUtf8());
//拼接大小/账号密码
    if(accoun.size()>9)
    {
        Regist.push_back(QByteArray::number(accoun.size()));
    }else{
        Regist.push_back("0");
        Regist.push_back(QByteArray::number(accoun.size()));
    }
    Regist.push_back(accoun);
    qDebug()<<"Regist value:"<<Regist<<endl;
    qint64 ret=Client->write(Regist);
 return ret>0 ?true :false;

}

LinkNetThread::LinkNetThread()
{

}

void LinkNetThread::run()
{
    QTimer *timer=new QTimer();
    timer->start(2000);
    connect(timer,&QTimer::timeout,this,[=]{
        emit tim();
    });
    exec();
}
